//
//  NBusinessServiceViewController.m
//  nncloud
//
//  Created by kabu on 2018/9/15.
//  Copyright © 2018年 youedata. All rights reserved.
#import "AddNewEquipmentViewController.h"
#import "equipDetailModel.h"
#import "ZFScanViewController.h"
#import "FilterViewController.h"
#import "RelayListModel.h"
#import "stationModel.h"
#import "UserCenterViewController.h"
#import "NDataInqueryViewController.h"
#import "NQiuzhiInfoDetailVC.h"
#import "NTongjiViewController.h"
#import "NMyQiyeViewController.h"
#import "NBusinessServiceViewController.h"
#import "RelayCell.h"
#import "RelayDetailViewController.h"
#import "LineNameView.h"
#import "LineSelectViewController.h"
@interface NBusinessServiceViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic,strong)LineNameView *lineName;
@property (nonatomic,strong)UITableView *tableView;
@property (nonatomic,strong)NSMutableArray *dataArray;
@property (nonatomic,strong)SearchBar *searchBar;
@property (nonatomic,assign)NSInteger currentPage;

@property (nonatomic,strong)NSMutableArray *dictArray;

@property (nonatomic,assign)BOOL isScan;

@property (nonatomic,copy)NSString *scanResult;
///列表名称
@property (nonatomic,strong)UILabel *ttLabel;

@end

#define kLineNumber 4
#define NavHeight 64
#define SectionHeaderHeight 65

#define cellIdentifier  @"relay"

@implementation NBusinessServiceViewController


-(UITableView *)tableView{
    if (!_tableView) {
        WeakStament(ws);
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0 , 64, ScreenWidth , ScreenHeight  - TabBarHeight-NavBarHeight-45) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.rowHeight = 132.0f;
        //        _tableView.separatorColor = [UIColor clearColor];
        _tableView.backgroundColor = kBackgroundColor;
        [_tableView registerNib:[UINib nibWithNibName:@"RelayCell" bundle:nil] forCellReuseIdentifier:cellIdentifier];
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
                    [ws refresh];
                }];
        
        ////如果是扫码进来的话没有分页
        if ([NUserModel shareInstance].comeinWithScan==NO) {
            _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
                [ws loadMoreData];
            }];
        }
        
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.tableFooterView = [UIView new];
        
    }
    return _tableView;
}


- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    ///
    [NUserModel shareInstance].equipType = @"s";
    
    
    self.searchBar.hidden = false;
    self.ttLabel.hidden = false;
    self.lineName.lineLab.text = [NUserModel shareInstance].currentLine?:@"";
    self.lineName.stationLab.text = [NUserModel shareInstance].currentStation?:@"";
    if ( [NUserModel shareInstance].currentSelect == YES) {
        [self refresh];
        [NUserModel shareInstance].currentSelect = false;
    }
    
    if ([NUserModel shareInstance].commitUpdate==YES) {
        [self refresh];
        [NUserModel shareInstance].commitUpdate = false;
    }
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    self.searchBar.hidden = YES;
    self.ttLabel.hidden = YES;
}
- (void)viewDidLoad {
    
    [super viewDidLoad];
    self.dataArray = [NSMutableArray array];
    self.dictArray = [NSMutableArray array];
    self.currentPage = 1;
    self.view.backgroundColor = kWhiteColor;
//    self.navigationItem.leftBarButtonItem = nil;
    [self.navigationItem setItemWithTitle:@"转辙机" textColor:kNavigationTitleColor fontSize:18 itemType:center];
//    [self addNavigationLeftButtonFrame:CGRectMake(0, 0, 25, 25) Image:WDImgName(@"我的") AndHighLightImage:nil AndText:@"" Target:self Action:@selector(headAction:)];
    [self addNavgationRightButtonWithFrame:CGRectMake(0, 0, 30, 30) title:@"" Image:@"nav_scan" selectedIMG:nil tartget:self action:@selector(scan)];
    [self.view addSubview:self.tableView];
    [self addSearchBar];
    ///站线选择条
    [self addLineNameView];
    [self addBottomBuyView];

    if ([NUserModel shareInstance].comeinWithScan==YES) {
        [self loadScanData];
    }else{
        [self loadData];
    }
    
}

///通过最外层的扫描进来的
-(void)loadScanData{
    
    ///这个接口调用了两次，在外面时是调用拿到器材类型，进来时候调用是拿到具体的器材信息
    [self.dataArray removeAllObjects];
    NSDictionary *dict = @{@"brokenNumber":[NUserModel shareInstance].scanBrokenNumber?:@""};
    [NNetworkClient postRequestWithBaseUrl:kScanUrl setParameters:dict success:^(id responseObject) {
        YYLog(@"%@",responseObject);
        if ([responseObject[@"status"]integerValue]==0) {
            
            NSArray *arr = responseObject[@"data"];
            for (NSDictionary *dict in arr) {
                equipDetailModel *model = [equipDetailModel mj_objectWithKeyValues:[dict deleteNull]];
                [self.dataArray addObject:model];
            }
            self.dictArray = [arr copy];
            [self.tableView reloadData];
            [SVProgressHUD dismiss];
            [self endRefresh];
            
            
            ///扫描用完一次本次bool 生命循环结束
            [NUserModel shareInstance].comeinWithScan = false;
            
            ///这个放的位置很重要  加载更多没有数据处理
            if (arr.count==0) {
                [self noMoreData];
            }
            
        }else{
            
            [AFToast showText:responseObject[@"message"]];
            
        }
    } fail:^(NSError *error) {
        
    } delegater:nil];
    
}


-(void)loadData {
    
    ///数组一定记得清空
    if (self.currentPage==1) {
        [self.dataArray removeAllObjects];
    }
    ///type 1继电器  2转辙机  3综合器材
    NSDictionary *dict;
    if (self.isScan==YES) {
        dict = @{@"type":@"2",@"brokenNumber":self.scanResult?:@"",@"stationName":[NUserModel shareInstance].currentStation?:@"",@"currentPage":@(self.currentPage)};
        self.isScan = false;
        
    }else{
        
        dict = @{@"type":@"2",@"brokenNumber":self.searchBar.textFd.text?:@"",@"stationName":[NUserModel shareInstance].currentStation?:@"",@"currentPage":@(self.currentPage)};
        
    }
    //    NSDictionary *dict = @{@"type":@"2",@"stationName":[NUserModel shareInstance].currentStation?:@"",@"brokenNumber":self.searchBar.textFd.text?:@"",@"currentPage":@(self.currentPage)};
    [SVProgressHUD show];
    [NNetworkClient postRequestWithBaseUrl:kInqueryStationUrl setParameters:dict success:^(id responseObject) {
        YYLog(@"%@",responseObject);
        if ([responseObject[@"status"]integerValue]==0) {
            NSArray *arr = responseObject[@"data"][@"lists"];
            for (NSDictionary *dict in arr) {
                //RelayListModel *model = [RelayListModel mj_objectWithKeyValues:dict];
                equipDetailModel *model = [equipDetailModel mj_objectWithKeyValues:[dict deleteNull]];
                [self.dataArray addObject:model];
            }
            self.dictArray = [arr copy];
            [self.tableView reloadData];
            [SVProgressHUD dismiss];
            [self endRefresh];
            ///这个放的位置很重要  加载更多没有数据处理
            if (arr.count==0) {
                [self noMoreData];
            }
        }
        
    } fail:^(NSError *error) {
        
        YYLog(@"%@",error);
        
    } delegater:nil];
    
}

#pragma mark - 添加搜索框
- (void)addSearchBar{
    SearchBar *bar = [[[NSBundle mainBundle]loadNibNamed:@"SearchBar" owner:self options:nil]lastObject];
    bar.frame = CGRectMake(100, 7, ScreenWidth-150, 30);
    bar.layer.cornerRadius = 15.f;
    bar.layer.masksToBounds = YES;
    bar.textFd.returnKeyType = UIReturnKeySearch;
    bar.textFd.delegate = self;
    self.searchBar = bar;
    [self.navigationController.navigationBar addSubview:bar];
    [bar.barBtn setTitle:@"请输入关键字搜索" forState:UIControlStateNormal];
    //    [bar.barBtn addTarget:self action:@selector(searchAction:) forControlEvents:UIControlEventTouchUpInside];
    
    UILabel *ttLabel = [[UILabel alloc]initWithFrame:CGRectMake(35, 3, 60, 36)];
    ttLabel.text = @"转辙机设备列表";
    ttLabel.font = kFont14;
    ttLabel.numberOfLines = 2;
    ttLabel.lineBreakMode = NSLineBreakByTruncatingTail;
    ttLabel.textColor = kWhiteColor;
    ttLabel.backgroundColor = kClearColor;
    [self.navigationController.navigationBar addSubview:ttLabel];
    self.ttLabel = ttLabel;
}
#pragma mark - 键盘  搜索  代理
//搜索虚拟键盘响应
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    NSLog(@"点击了搜索");
    [self.searchBar.textFd resignFirstResponder];
    //进行搜索
    [self refresh];
    return YES;
}
- (BOOL)textFieldShouldClear:(UITextField *)textField{
    
    YYLog(@"点击了清空按钮");
    [self.view endEditing:YES];
    self.searchBar.textFd.text = @"";
    [self refresh];
     [self.tableView scrollsToTop];
    return YES;
    
}

- (void)backItemClick{
//    [self headAction:nil];
    [self.tabBarController.navigationController popViewControllerAnimated:NO];
}
#pragma mark - 点击头像
- (void)headAction:(UIButton *)btn{
//    UserCenterViewController *center = [UserCenterViewController new];
//    [self.navigationController pushViewController:center animated:YES];
}

//扫码
- (void)scan {
    ///扫码
    ZFScanViewController * vc = [[ZFScanViewController alloc] init];
    vc.returnScanBarCodeValue = ^(NSString * barCodeString){
        [AFToast showText:barCodeString];
        //        self.resultLabel.text = [NSString stringWithFormat:@"扫描结果:\n%@",barCodeString];
        if (barCodeString.length>5) {
            self.scanResult = barCodeString;
            self.isScan = YES;
            [self loadData];
        }else{
            [AFToast showText:@"当前扫描结果无效"];
        }
    };
    [self presentViewController:vc animated:YES completion:nil];
}
- (void)refresh {
    self.currentPage = 1;
    [self loadData];
}
- (void)loadMoreData{
    self.currentPage++;
    [self loadData];
}
- (void)endRefresh {
    [self.tableView.mj_header endRefreshing];
    [self.tableView.mj_footer endRefreshing];
}

- (void)noMoreData {
    [self.tableView reloadData];
    [self.tableView.mj_footer endRefreshingWithNoMoreData];
}


#pragma mark - datasource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
        return self.dataArray.count;
//    return 10;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    RelayCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
//    RelayListModel *model = self.dataArray[indexPath.row];
    equipDetailModel *model = self.dataArray[indexPath.row];
    cell.zhanmingOrQuxiangLab.text = @"去向";
    cell.weizhiOrChahaoLab.text = @"岔号";
    if (self.dataArray.count>indexPath.row) {
        cell.bianhaoLab.text = model.shebeibianhao;
        cell.xinghaoLab.text = model.shebeixinghao;
        cell.stationLab.text = model.quxiang;
        cell.positionLab.text = model.chahao;
        cell.typeNameLabel.text = model.shebeizhonglei;
    }
    return cell;
}


#pragma mark - delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    equipDetailModel *model = self.dataArray[indexPath.row];
    RelayDetailViewController *proc = [RelayDetailViewController new];
    [NUserModel shareInstance].printType = @"s";
    proc.model = model;
    proc.flag = @"s";
    [self.navigationController pushViewController:proc animated:YES];
}

#pragma mark - 添加线名view
-(void)addLineNameView{
    self.lineName = [[[NSBundle mainBundle]loadNibNamed:@"LineNameView" owner:self options:nil]lastObject];
    self.lineName.frame = CGRectMake(0, 0, ScreenWidth, 62);
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapLineAction:)];
    [self.lineName addGestureRecognizer:tap];
    
    [self.view addSubview:self.lineName];
    [self.view bringSubviewToFront:self.lineName];
    
    UIView *bar = [[UIView alloc]initWithFrame:CGRectMake(0, 62, ScreenWidth, 4)];
    bar.backgroundColor = kBackgroundColor;
    [self.view addSubview:bar];
    
}

#pragma mark - 点击进入线别选择
- (void)tapLineAction:(UITapGestureRecognizer *)tap{
    
    LineSelectViewController *ses = [[LineSelectViewController alloc]init];
    [self.navigationController pushViewController:ses animated:YES];
}
#define BarHeight 45.f
///添加底部bar
- (void)addBottomBuyView{
    
    UIButton *cartBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    cartBtn.frame = CGRectMake(0, ScreenHeight-BarHeight-TabBarHeight-NavBarHeight, ScreenWidth/2-1, BarHeight);
    cartBtn.backgroundColor = kSystemtBlue;
    [cartBtn addTarget:self action:@selector(cartAction:) forControlEvents:UIControlEventTouchUpInside];
    [cartBtn setTitle:@"筛选" forState:UIControlStateNormal];
    [self.view addSubview:cartBtn];
    
    UIButton *gouBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    gouBtn.frame = CGRectMake(ScreenWidth/2, ScreenHeight-BarHeight-TabBarHeight-NavBarHeight, ScreenWidth/2, BarHeight);
    gouBtn.backgroundColor = kSystemtBlue;
    [gouBtn addTarget:self action:@selector(gouAction:) forControlEvents:UIControlEventTouchUpInside];
    [gouBtn setTitle:@"新增设备" forState:UIControlStateNormal];
    [self.view addSubview:gouBtn];
}
#pragma mark - 筛选
///筛选
- (void)cartAction:(UIButton *)btn
{
    equipDetailModel *model = [self.dataArray firstObject];
    FilterViewController *filter = [FilterViewController new];
    filter.flag = @"s";
    filter.model = model;
    [self.navigationController pushViewController:filter animated:YES];
}
#pragma mark - 新增设备
- (void)gouAction:(UIButton *)btn
{
    
    equipDetailModel *model = [self.dataArray firstObject];
    AddNewEquipmentViewController *add = [AddNewEquipmentViewController new];
    add.flag = @"s";
    add.model = model;
    [self.navigationController pushViewController:add animated:YES];
    
}


@end
